#!/usr/bin/env python3
"""
添加缺失的路由数据
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import engine
from app.models.auth import Route
from sqlalchemy import select
from datetime import datetime

# 需要添加的路由数据
MISSING_ROUTES = [
    {
        'path': '/roles',
        'name': 'roles',
        'display_name': '角色管理',
        'description': '系统角色管理',
        'icon': 'TeamOutlined',
        'component': 'RoleManagement',
        'parent_path': '/system',
        'sort_order': 2,
        'is_menu': True,
    },
    {
        'path': '/permissions',
        'name': 'permissions',
        'display_name': '权限管理',
        'description': '系统权限管理',
        'icon': 'SafetyOutlined',
        'component': 'PermissionManagement',
        'parent_path': '/system',
        'sort_order': 3,
        'is_menu': True,
    },
    {
        'path': '/routes',
        'name': 'routes',
        'display_name': '路由管理',
        'description': '系统路由配置管理',
        'icon': 'BranchesOutlined',
        'component': 'RouteManagement',
        'parent_path': '/system',
        'sort_order': 4,
        'is_menu': True,
    },
    {
        'path': '/showcase',
        'name': 'showcase',
        'display_name': 'UI展示',
        'description': 'UI组件展示页面',
        'icon': 'AppstoreOutlined',
        'component': 'UIShowcase',
        'parent_path': None,
        'sort_order': 7,
        'is_menu': True,
    }
]

async def add_missing_routes():
    """添加缺失的路由"""
    async with AsyncSession(engine) as db:
        try:
            print("🚀 开始添加缺失的路由...")
            
            # 获取现有路由
            stmt = select(Route)
            result = await db.execute(stmt)
            existing_routes = result.scalars().all()
            existing_paths = {route.path for route in existing_routes}
            path_to_id = {route.path: route.id for route in existing_routes}
            
            added_count = 0
            
            for route_data in MISSING_ROUTES:
                if route_data['path'] in existing_paths:
                    print(f"⏭️  路由 {route_data['path']} 已存在，跳过")
                    continue
                
                # 获取父路由ID
                parent_id = None
                if route_data['parent_path']:
                    parent_id = path_to_id.get(route_data['parent_path'])
                    if not parent_id:
                        print(f"❌ 父路由 {route_data['parent_path']} 不存在，跳过 {route_data['path']}")
                        continue
                
                # 创建路由
                route = Route(
                    path=route_data['path'],
                    name=route_data['name'],
                    display_name=route_data['display_name'],
                    description=route_data['description'],
                    icon=route_data['icon'],
                    component=route_data['component'],
                    parent_id=parent_id,
                    sort_order=route_data['sort_order'],
                    is_menu=route_data['is_menu'],
                    is_active=True,
                    is_system=True
                )
                
                db.add(route)
                added_count += 1
                print(f"✅ 添加路由: {route_data['path']} - {route_data['display_name']}")
            
            await db.commit()
            print(f"🎉 成功添加 {added_count} 个路由")
            
        except Exception as e:
            print(f"❌ 添加路由失败: {e}")
            await db.rollback()
            raise

async def main():
    """主函数"""
    try:
        await add_missing_routes()
        print("✅ 路由添加完成！")
        
    except Exception as e:
        print(f"❌ 操作失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    asyncio.run(main())
